package dome2;

public class HashBuck {
    public static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public static int useSize = 0;
    public static final float LOAD_FACTOR = 0.75f;

    public void put(int key,int val) {
        //1.通过哈希函数找到一个位置
        int index = key % array.length;

        //2.判断当前数组下标的链表  有没有Key相同的 如果有 更新val
        Node cur = array[index];
        while(cur!=null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //3.如果没有  进行尾插法
        Node node = new Node(key,val);
        cur = array[index];
        if(array[index] == null) {
            array[index] = node;
        }else {
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
        }
        useSize++;

        //4.计算一下当前的负载因子  如果超过了0.75 那么就需要扩容
        if(doLoadFactor() >= LOAD_FACTOR) {
            //扩容
            //array = Arrays.copyOf(array,array.length*2);  error
            resize();
        }
    }

    private float doLoadFactor() {
        return 1.0f * useSize / array.length;
    }

    private void resize() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur!=null) {
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                if(newArray[newIndex] == null) {
                    newArray[newIndex] = cur;
                    cur.next = null;
                }else {
                    Node tmp = newArray[newIndex];
                     while(tmp.next!=null) {
                         tmp = tmp.next;
                     }
                     tmp.next = cur;
                     cur.next = null;
                }
                cur = curN;
            }
        }
        array = newArray;
    }

    public int get(int key) {
        //1.通过哈希函数找到一个位置
        int index = key % array.length;

        //2.判断当前数组下标的链表  有没有Key相同的 如果有 更新val
        Node cur = array[index];
        while(cur!=null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
